# _*_coding:utf-8 _*_

from ESL import *
import string
import time
import random
from loguru import logger
from flask import request, jsonify
import traceback


print("********卓越CC-CALL模块加载成功**********")

'''日志打印程序'''

logger.add('./log/cc_call_file_{time}.log', format="{time} {name} {level} {message}", level="INFO", rotation='10 MB',
           encoding='utf-8')  # 根据时间为日志命名，每10MB新建一个

# 连接的fs服务器信息
hostIp = '127.0.0.1'
fsport = '9088'
fsuser = 'Zyunfs'


'''连接fs执行命令函数'''


def fscmd(fsml):
    apicon = ESLconnection(hostIp, fsport, fsuser)
    if apicon.connected():
        api = apicon.send(fsml)
        apicon.disconnect()
        logger.warning(fsml)
        return 200
    else:
        logger.error('fsesl连接不成功')
        return 0


'''呼叫接口'''


def apicall(myjson):
    try:
        appid = myjson.get("appid")
        calltype = myjson.get("callType")
        caller = myjson.get("caller")
        called = myjson.get("called")
        displayCallerNum = myjson.get("displayCallerNum", 'aaa')
        displayCalledNum = myjson.get("displayCalledNum", 'aaa')
        data1 = myjson.get("data1", 'no')
        data2 = myjson.get("data2", 'no')
        print(displayCallerNum, data1, data2)
        print(calltype)
        call_id = ''.join(random.sample(string.ascii_letters + string.digits, 16)) + str(time.time())
        if calltype == 'inout':
            fsml = ('bgapi originate {callType=' + calltype +
                    ',caller=' + caller +
                    ',called=' + called +
                    ',appid=' + appid +
                    ',data1=' + data1 +
                    ',data2=' + data2 +
                    ',zynmb=' + appid +
                    ',origination_caller_id_name=' + displayCallerNum +
                    ',origination_caller_id_number=' + displayCallerNum +
                    ',displayCalledNum=' + displayCalledNum +
                    ',origination_uuid=' + call_id +
                    '}user/' + caller +
                    ' ' + called
                    )
            print(fsml)
            fsc = fscmd(fsml)
            if fsc:
                return {'msg': 'success', 'code': '200', 'data': ''}
            else:
                return {'msg': 'error', 'code': '153', 'data': ''}

        elif calltype == 'outout':
            gw = myjson.get("gatewayb", 'zy1')
            fsml = ('bgapi originate {callType=' + calltype +
                    ',caller=' + caller +
                    ',called=' + called +
                    ',appid=' + appid +
                    ',data1=' + data1 +
                    ',data2=' + data2 +
                    ',zynmb=' + appid +
                    ',ignore_early_media=true,origination_caller_id_name=' + displayCallerNum +
                    ',origination_caller_id_number=' + displayCallerNum +
                    ',displayCalledNum=' + displayCalledNum +
                    ',origination_uuid=' + call_id +
                    '}sofia/gateway/' + gw +
                    '/' + caller +
                    ' ' + called
                    )
            print(fsml)
            fsc = fscmd(fsml)
            if fsc:
                return {'msg': 'success', 'code': '200', 'data': ''}
            else:
                return {'msg': 'error', 'code': '153', 'data': ''}

        elif calltype == 'outin':
            gw = myjson.get("gatewayb", 'zy1')
            fsml = ('bgapi originate {callType=' + calltype +
                    ',caller=' + caller +
                    ',called=' + called +
                    ',appid=' + appid +
                    ',data1=' + data1 +
                    ',data2=' + data2 +
                    ',zynmb=' + appid +
                    ',ignore_early_media=true,origination_caller_id_name=' + displayCallerNum +
                    ',origination_caller_id_number=' + displayCallerNum +
                    ',displayCalledNum=' + displayCalledNum +
                    ',origination_uuid=' + call_id +
                    '}sofia/gateway/' + gw +
                    '/' + caller +
                    ' &' + called
                    )
            print(fsml)
            fsc = fscmd(fsml)
            if fsc:
                return {'msg': 'success', 'code': '200', 'data': ''}
            else:
                return {'msg': 'error', 'code': '153', 'data': ''}
        else:
            logger.error('callType不正确')
            return jsonify(
                {'msg': 'error', 'code': '152', 'data': 'callType不正确'})

    except Exception as ek:
        logger.error("非token外呼错误:")
        logger.error(ek)
        logger.error(traceback.format_exc())


'''fs通用命令接口'''


def command():
    try:
        myjson = request.get_json()
        appid = myjson.get("appid")
        secr = myjson.get("secret")
        command = myjson.get("command")
        # data = myjson.get("data")
        gateway = myjson.get("gateway")
        request_id = ''.join(random.sample(string.ascii_letters + string.digits, 16)) + str(time.time())
        apicon = ESLconnection(hostIp, fsport, fsuser)
        if apicon.connected():
            apidata = apicon.sendRecv(command)
            jbody = apidata.getHeader("_body")
            apicon.disconnect()
            return jsonify(
                {'msg': 'success', 'code': '200', 'data': str(jbody)})
        else:
            return jsonify(
                {'msg': 'error', 'code': '133', 'data': '连接失败'})
    except Exception as e:
        logger.error("查坐席状态监控错误:")
        logger.error(e)
        logger.error(traceback.format_exc())
